package org.action.news;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.action.BaseAction;
import org.biz.news.IHomeBiz;
import org.hibernate.entity.Column;
import org.hibernate.entity.Links;
import org.hibernate.entity.NewsContents;
import org.hibernate.entity.NewsTitle;
import org.hibernate.entity.Suggestion;
import org.util.Json;

import common.util.page.WebPagination;

/**
 * 
 * 前台首页控制器
 * 
 * @Title: HomeAction.java
 * @Description:新闻系统(一期)
 * @Copyright: Copyright (c) 2011
 * @Company:乐易考
 * @author zhangliming
 * @date Oct 23, 2012 10:55:01 AM
 * @version V4.0
 * @param <NewsContents>
 */

public class HomeAction extends BaseAction {

	private static final long serialVersionUID = -2023652309990788069L;

	private IHomeBiz homeBiz = null; // 业务类对象;

	private WebPagination page = new WebPagination();

	/** 子栏目 */
	private List<Column> lstChannelColumns = new ArrayList<Column>();
		
	
	/** 栏目id(辅助) */
	private String strColumnsID = ",";
	/** 第一个重点展示 区的新闻条数  */
	//private Integer intFstCNewsLimit = 6;
	/** 其它的重点展示区的新闻条数  */
	//private Integer intOtherCNewsLimit = 6;
	/** 最新文章 */
	//private Integer intArticlesLimit = 5;
	/** (20131224 add by xy)  end... */
	
	private Integer DYNAMIC = 1 ; // 通知公告
	private Integer LOW = 1 ; // 通知公告
	private Integer HONOR = 2; //政策文件
	private Integer NWS = 6 ; // 新闻资讯
	private Integer JOB = 7 ; // 工作动态
	
	private Integer BASE = 9 ; // 创业基地
	private Integer GUES = 10 ; // 创客之家
	
	private Integer STU = 12 ; // 学习园地
	private Integer CYZ = 13 ; // 创业指南
	private Integer DOW = 14 ; // 下载专区
	private String TJ="6,7";//栏目推荐文章

	
	public WebPagination getPage() {
		return page;
	}

	public void setPage(WebPagination page) {
		this.page = page;
	}

	public IHomeBiz getHomeBiz() {
		return homeBiz;
	}

	public void setHomeBiz(IHomeBiz homeBiz) {
		this.homeBiz = homeBiz;
	}


	public List<Column> getLstChannelColumns() {
		return lstChannelColumns;
	}

	public void setLstChannelColumns(List<Column> lstChannelColumns) {
		this.lstChannelColumns = lstChannelColumns;
	}

	/**
	 * 查看新闻首页
	 * 
	 * @return
	 */
	public String toHome() {	
		this.friends(); // 友情链接
		// this.newsArticle(); // 最新文章;
		//this.tuijian(); // 关注频道推荐文章;
		//this.otherColumn(); // 其它栏目的文章;
		//this.initNewsetArticle();// 最新文章
		//this.initAD();// 网站公告
		//this.initImportParts();// 重要展示模块
		// 幻灯片
//		this.initSlideShow();
		this.initPartyBuild();
		this.initMenu();
		return "toHome";
	}
	private void initMenu(){
		lstChannelColumns=null;
		lstChannelColumns=this.homeBiz.listChildColumns();
		List<Column> towColumns=new ArrayList();
		List<Column> threeColumns=new ArrayList();
		for(Column fc:lstChannelColumns){
			fc.setParentId(fc.getMenuColumns()==null?null:fc.getMenuColumns().getId());

			if(fc.getParentId()!=null){
				for(Column fcc:lstChannelColumns){
					if(fcc.getId().equals(fc.getParentId())){
						if(fcc.getParentId()==null){
							towColumns.add(fc); 
							break;
						}else{
							threeColumns.add(fc);break;
						}
					}
				}
			}
				
		}
		for(Column fc:lstChannelColumns){
			for(Column towfc:towColumns){
				if(fc.getId().equals(towfc.getParentId())){
					fc.ischi=true;
				}
			}
		}
		this.set("towColumns", towColumns);
		this.set("threeColumns", threeColumns);
	}
	/**
	 * 专题
	 * 
	 * @return
	 */
	public String tozt() {
		// 幻灯片
		this.initSlideShow();
		return "tozt";
	}

	/**
	 * 友情链接
	 * 1:省厅，2：大学，3：企业
	 */
	public void friends() {
		this.set("friends_st", this.homeBiz.selFriends(1));
	}

	/**
	 * 栏目推荐文章5篇
	 * @param cid 一级栏目ID
	 * @param pageSize 
	 * @return
	 */
	public List<NewsTitle> parentTuijian(String cid) {
		// 一条关注频道的推荐文章;
		return this.homeBiz.selNewsTJByCid(cid);
		// 几条关注频道的置顶文章;
		//this.set("topNews", this.homeBiz.selNewsTopByCid(1, 2));

	}
	
	/**
	 * 以及目录关注频道推荐文章
	 */
	public List<NewsTitle> childTuijian(Integer cid) {
		Column col = this.homeBiz.findColumnObject(cid); // 获取栏目对象
		strColumnsID = ","; 
		gainColumnsID(col);
		strColumnsID = strColumnsID.substring(1,strColumnsID.length()-1);
		return this.homeBiz.selNewsTJByCid(strColumnsID);
	}
	

	/**
	 * 其它栏目的数据
	 */
	public void otherColumn() {
		// 关注栏目;
		/*this.set("guzhupic", this.homeBiz.selColumnPic(1));
		this.set("guzhunew", this.homeBiz.selColumnNews(1, 5));

		// 观点栏目;
		this.set("guandianpic", this.homeBiz.selColumnPic(2));
		this.set("guandiannew", this.homeBiz.selColumnNews(2, 5));

		// 培训管理
		this.set("peixunpic", this.homeBiz.selColumnPic(3));
		this.set("peixunnew", this.homeBiz.selColumnNews(3, 5));

		// 讲师文库
		this.set("jiangshipic", this.homeBiz.selColumnPic(4));
		this.set("jiangshinew", this.homeBiz.selColumnNews(4, 5));

		// 企业大学
		this.set("qiyepic", this.homeBiz.selColumnPic(5));
		this.set("qiyenew", this.homeBiz.selColumnNews(5, 5));

		// E-learning
		this.set("learningpic", this.homeBiz.selColumnPic(6));
		this.set("learningnew", this.homeBiz.selColumnNews(6, 5));

		// 快讯
		this.set("kuaixunpic", this.homeBiz.selColumnPic(7));
		this.set("kuaixunnew", this.homeBiz.selColumnNews(7, 5));*/

	}

	/**
	 * 联系我们
	 * 
	 * @return
	 */
	public String toContact() {
		this.initMenu();
		return "toContact";
	}
	/**
	 * 关于我们
	 * 
	 * @return
	 */
	public String toAbout() {
		this.initMenu();
		return "toAbout";
	}
	/**
	 * 安全退出
	 * 
	 * @return
	 */
	public String doExit() {
		request.getSession().removeAttribute("onlineUser");
		return this.toHome();
	}
	
	/**
	 * 幻灯片展示
	 */
	private void initSlideShow(){
		
		// 幻灯片对应的文字描述
		List<String> lstSlidershowPicDes =  new ArrayList<String>();
		// 幻灯片图片存放路径
		List<String> lstSlideshowPicUrl = new ArrayList<String>();
		// 幻灯片指向路径
		List<String> lstSlideShowToUrl = new ArrayList<String>();
		// 幻灯片
		List<Links> lstSlideshow = this.homeBiz.searchSlides();

		if(lstSlideshow != null && lstSlideshow.size() != 0){
			for(Links ti : lstSlideshow){
				lstSlidershowPicDes.add(ti.getTheme());
				lstSlideshowPicUrl.add(ti.getPic());
				lstSlideShowToUrl.add(ti.getUrl());
			}
			this.set("lstSlidershowPicDes", lstSlidershowPicDes);
			this.set("lstSlideshowPicUrl",lstSlideshowPicUrl);
			this.set("lstSlideShowToUrl",lstSlideShowToUrl);
		} else {
			//System.out.println("初始化幻灯片模块失败.........");
		}
	}
	
	/**
	 * 公告展示
	 */
	/*private void initAD(){
		List<Links> lstImportAD = homeBiz.searchAds();
		this.set("lstImportAD",lstImportAD);
	}*/
	
	/**
	 * 重要展示模块(首页面有6个重要展示模块，顺序为从上到下，从左到右)
	 * 标识为NewsTitle：newType
	 */
/*	private void initImportParts(){
		
		// 1
		List<Column> lstFstPartsColumn = new ArrayList<Column>();
		List<List<NewsTitle>> lstFstNewsTitle = new ArrayList<List<NewsTitle>>();
		List<List<Column>> lstOtherPartsColumn = new ArrayList<List<Column>>();
		List<List<NewsTitle>> lstOtherNewsTitle = new ArrayList<List<NewsTitle>>();
		List<Column> lstLastPartsColumn = new ArrayList<Column>();
		List<List<NewsTitle>> lstLastNewsTitle = new ArrayList<List<NewsTitle>>();
		List<Column> lstParentColumn = this.homeBiz.searchImportParts(); 
		// 找出子栏目以及父栏目下的新闻（这里的新闻是父栏目本身的 新闻和子栏目新闻的总和）
		if(lstParentColumn!=null) {
			int intIndex = 0;
			//System.out.println("size:" +lstParentColumn.size() );
			for(Column parentColumn : lstParentColumn) {
				if(intIndex == 0 || (intIndex == lstParentColumn.size()-1)){
					List<Column> lstColumn = this.homeBiz.listChildColumns(parentColumn);
					//System.out.println("1:" +lstColumn.size());
					// 子栏目
					if(lstColumn!=null) {
						// 需要把父栏目也放进去
						if(intIndex == lstParentColumn.size()-1){
							//lastPartsMap.put(parentColumn,new ArrayList<NewsTitle>());
							lstLastPartsColumn.add(parentColumn);
							lstLastNewsTitle.add(new ArrayList<NewsTitle>());
						}
						for(Column childColumn : lstColumn){
							strColumnsID = childColumn.getId().toString();
							// 新闻标题
							List<NewsTitle> lstNewsTitle = this.homeBiz.selNewsByColumn(strColumnsID,1,intFstCNewsLimit);
							if(intIndex == 0){
								//fstPartsMap.put(childColumn, lstNewsTitle);
								lstFstPartsColumn.add(childColumn);
								if(lstNewsTitle!=null)	
									lstFstNewsTitle.add(lstNewsTitle);
								else 
									lstFstNewsTitle.add(new ArrayList<NewsTitle>());
							} else {
								//lastPartsMap.put(childColumn,lstNewsTitle);
								lstLastPartsColumn.add(childColumn);
								//System.out.println("lstNewsTitle:" + lstNewsTitle.size());
								if(lstNewsTitle!=null)
									lstLastNewsTitle.add(lstNewsTitle);
								else 
									lstLastNewsTitle.add(new ArrayList<NewsTitle>());
							}
						}
						
					}
				} else if(intIndex < lstParentColumn.size()-1){
					//System.out.println("2");
					// 清空strColumnsID
					strColumnsID = ",";
					gainColumnsID(parentColumn);
					// 去掉开始的逗号和结尾的逗号
					strColumnsID =  strColumnsID.substring(1,strColumnsID.length()-1);
					boolean blnHasNotPic = false;
					// 查找总的新闻（顺序为置顶，发布时间，id）
					List<NewsTitle> lstNewsTitlePic = this.homeBiz.selNewsByColumn(strColumnsID,1,1,blnHasNotPic);
					List<NewsTitle> lstNewsTitleNoPic = null;
					if(lstNewsTitlePic!=null && lstNewsTitlePic.size()!=0){
						System.out.println(lstNewsTitlePic.get(0).getTitle());
						lstNewsTitleNoPic = this.homeBiz.selNewsByColumn(strColumnsID,1,intOtherCNewsLimit,true,lstNewsTitlePic.get(0).getId());
					} else {
						lstNewsTitleNoPic = this.homeBiz.selNewsByColumn(strColumnsID,1,intOtherCNewsLimit);
					}
					List<Column> lstChannelColumns = this.homeBiz.listChildColumns(parentColumn);
					lstChannelColumns.add(0,parentColumn);
					//otherPartsMap.put(lstChannelColumns, lstNewsTitle);
					lstOtherPartsColumn.add(lstChannelColumns);
					if(lstNewsTitlePic!=null && lstNewsTitlePic.size()!=0){
						if(lstNewsTitleNoPic!=null){
							lstNewsTitleNoPic.add(0, lstNewsTitlePic.get(0));
						}
						lstOtherNewsTitle.add(lstNewsTitleNoPic);
					} else {
						if(lstNewsTitleNoPic!=null){
							lstNewsTitleNoPic.add(0, new NewsTitle());
							lstOtherNewsTitle.add(lstNewsTitleNoPic);
						}
					}
				}
				intIndex++;
			}
			this.set("lstFstPartsColumn", lstFstPartsColumn);
			this.set("lstFstNewsTitle", lstFstNewsTitle);
			
			this.set("lstOtherPartsColumn", lstOtherPartsColumn);
			this.set("lstOtherNewsTitle", lstOtherNewsTitle);
			
			this.set("lstLastPartsColumn", lstLastPartsColumn);
			this.set("lstLastNewsTitle", lstLastNewsTitle);
		} else {
			//System.out.println("初始化重点模块失败.....");
		}
		
	}*/
	
	/**
	 * 获得其子孙栏目的ID
	 * 在这里要进行甄别操作，不能出现其子类是其父类（这是错误操作导致的结果）的情况
	 */
	private void gainColumnsID(Column menuColumns){
		
		if(menuColumns!=null){
			List<Column> lstTempMenuColumns = this.homeBiz.listChildColumns(menuColumns);
			// 先判断此时id是否已经出现在字符串内部，如果出现，则表明栏目有问题
			if(!strColumnsID.contains("," + menuColumns.getId().intValue()  +",")){
				// 栏目id以逗号分隔开
				strColumnsID += menuColumns.getId()+",";
				if(lstTempMenuColumns != null && lstTempMenuColumns.size() != 0) {
					for(Column tempMenuColumn : lstTempMenuColumns){
						gainColumnsID(tempMenuColumn);
					}
				}
			} else {
//				logger.error(this.getClass());
//				logger.error("Method getChildrenID : id 为" + menuColumns.getId()+ "的栏目，其上级栏目中曾出现此栏目" );
			}
		}
	}
	/**
	 * 
	 * 建党栏目
	 */
	@SuppressWarnings("unused")
	private void initPartyBuild(){
		List<NewsTitle> lstLow = handleColumnsParentNews(LOW,1,6);
		List<NewsTitle> lstHonor = handleColumnsNews(HONOR,1,6);
		List<NewsTitle> lstNew = handleColumnsParentNews(NWS,1,6);
		List<NewsTitle> lstJob = handleColumnsParentNews(JOB,1,6);
		List<NewsTitle> lstEnterprise = handleColumnsParentNews(BASE,1,6);
		List<NewsTitle> lstGuest = handleColumnsNews(GUES,1,6);
		List<NewsTitle> lstStudy = handleColumnsParentNews(STU,1,6);
//		List<NewsTitle> lstCyz = handleColumnsParentNews(CYZ,1,3);
		List<NewsTitle> lstDown = handleColumnsParentNews(DOW,1,6);
//		List<Suggestion> lstSuggestion = handleSuggention(1,5);
		
		this.set("lowNews", lstLow);
		this.set("lowNews_tj", this.parentTuijian(TJ));
		this.set("honorNews", lstHonor);
//		this.set("honorNews_tj", this.childTuijian(HONOR));
		this.set("infNews", lstNew);
//		this.set("infNews_tj", this.parentTuijian(NWS));
		this.set("jobNews", lstJob);
//		this.set("jobNews_tj", this.parentTuijian(JOB));
		this.set("enterNews", lstEnterprise);
		this.set("guestNews", lstGuest);
//		this.set("sugeNews", lstSuggestion);
		this.set("studyNews", lstStudy);
//		this.set("cyzNews", lstCyz);
		this.set("downNews", lstDown);
		this.set("dynamic",this.findPartNews(DYNAMIC));
	}
	
	
	
	/**
	 * 查询有子节点栏目
	 * @param cid
	 * @return
	 */
	private List<NewsTitle> handleColumnsNews(Integer cid,Integer star,Integer end){
		Column col = this.homeBiz.findColumnObject(cid); // 获取栏目对象
		strColumnsID = ","; 
		gainColumnsID(col);
		strColumnsID = strColumnsID.substring(1,strColumnsID.length()-1);
		return this.homeBiz.findPartNews(strColumnsID,star,end,true);
	}
	
	/**
	 * 无子节点栏目
	 * @param pid
	 * @return
	 */
	private List<NewsTitle> handleColumnsParentNews(Integer pid,Integer star,Integer end){
		return this.homeBiz.findPartNews(String.valueOf(pid),star,end,true);
		
	}
	
	/**
	 * 问答栏目
	 * @param pid
	 * @return
	 */
	private List<Suggestion> handleSuggention(Integer star,Integer end){
		return this.homeBiz.findSuggestion(star,end,true);
	}
	
	private List<NewsTitle> handleColumnsParentNews1(Integer pid){
		Column col = this.homeBiz.findColumnObject(pid); // 获取栏目对象
		strColumnsID = ","; 
		gainColumnsID(col);
		strColumnsID = strColumnsID+24;
		strColumnsID = strColumnsID.substring(1,strColumnsID.length());
		return this.homeBiz.findPartNews(strColumnsID,1,3,true);
	}
	private List<NewsTitle> handleColumnsParentNews2(Integer pid){
		Column col = this.homeBiz.findColumnObject(pid); // 获取栏目对象
		strColumnsID = ","; 
		gainColumnsID(col);
		strColumnsID = strColumnsID+24;
		strColumnsID = strColumnsID.substring(1,strColumnsID.length());
		return this.homeBiz.findPartNews(strColumnsID,2,3,true);
	}
	private Map<List<NewsTitle>,List<NewsContents>> findPartNews(Integer cid){
		Map<List<NewsTitle>,List<NewsContents>> map = new HashMap<List<NewsTitle>,List<NewsContents>>();
		Column col = this.homeBiz.findColumnObject(cid); // 获取栏目对象
		strColumnsID = ","; 
		gainColumnsID(col);
		strColumnsID = strColumnsID.substring(1,strColumnsID.length()-1);
		List<NewsTitle> nt = this.homeBiz.findPartNews(strColumnsID,1,1,true);
		if(nt != null && !("".equals(nt)) && nt.size() > 0){
		  Integer tid = nt.iterator().next().getId();
		  if(tid != null && !("".equals(tid))){
			List<NewsContents> nc = this.homeBiz.findContentsByTid(tid,1,4);
			map.put(nt, nc); 
		  }		
		}
		return map;	
	}
	
	/**
	 * 搜索
	 * @author 刘丽娜
	 * 20160506
	 * @return
	 */
	public String toSearch() {
		HttpServletRequest request = getRequest();
		String searchText = request.getParameter("key_word");
		
		this.page.setCount(this.homeBiz.doCountSearch(searchText.trim()));
		this.page.setPageSize(10);
		//Map<String, List<NewsTitle>> mapSearchResult = new LinkedHashMap<String, List<NewsTitle>>();
		//mapSearchResult.put(searchText, this.homeBiz.selBySearch(searchText.trim(),this.page.getPageNo(), this.page.getPageSize()));
		//this.set("lists", mapSearchResult);
		List<NewsTitle> searchlistList = this.homeBiz.selBySearch(searchText.trim(),1, this.page.getCount());
		this.set("lists", searchlistList);
		this.page.setUrl(request.getContextPath() + "/search/"+searchText.trim());
		this.set("page_style", this.page.newsPros());
		//加载菜单
		this.initMenu();
		return "toSearch";
	}

}

   
